// 代理请求服务转发中间件
const http = require("http");
module.exports = function ({ target, pathRewrite }) {
  return function (req, res) {
    try {
      // console.log("proxyMiddleware", req.path);
      const { hostname, port} = new URL(target);
      // console.log("url", url);
      let path = req.path
      if (pathRewrite && typeof pathRewrite === "function") {
        path = pathRewrite(req.path);
      }
      const options = {
        hostname,
        port,
        path,
        method: req.method,
        headers: req.headers,
      };
      const proxyReq = http.request(options, (response) => {
        // 代理响应对象 response
        res.status(response.statusCode);
        for (const key in response.headers) {
          res.setHeader(key, response.headers[key]);
        }
        response.pipe(res); // 响应结果写入到res中
      });
      req.pipe(proxyReq); //把请求体写入到代理请求对象的请求体中
    } catch (error) {
      throw new Error(error.message);
    }
  };
};
